package cn.touna.jss.modules.third.linkface;

import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.properties.disconf.LinkfaceProperties;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.third.linkface.entity.LinkFaceRequestEntity;
import cn.touna.jss.modules.third.linkface.enums.LinkFaceEnum;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.exception.ServiceException;
import cn.touna.risk.api.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 人脸识别
 * <p>
 * Created by wuwc on 2017/7/14.
 */
@Service
public class LinkfaceService {

    private static final Logger logger = LogManager.getLogger(LinkfaceService.class);

    @Autowired
    private LinkfaceProperties linkfaceConfig;

    /**
     * linkfack人脸比对
     * 不需要做缓存，且请求历史在其他地方已做
     * @param requestEntity
     * @return
     */
    @ApiMapping(value = "authFaceVerify.linkFaceVerify",useCache = false,recordHistory = false,desc = "商汤.人脸识别")
    public Response livenessVerification(LinkFaceRequestEntity requestEntity, MultipartFile uploadFile) {
        logger.info("REQ 【linkfack人脸比对】livenessVerification-requestEntity：{}", requestEntity);
        Response<String> response = new Response<>();
        try {
            if (null == uploadFile) {
                throw new ServiceException("人脸识别文件不能为空");
            }
            HttpEntity entity = MultipartEntityBuilder
                    .create()
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .addTextBody("api_id", linkfaceConfig.getApiId(), ContentType.TEXT_PLAIN)
                    .addTextBody("api_secret", linkfaceConfig.getApiSecret(), ContentType.TEXT_PLAIN)
                    .addTextBody("name", requestEntity.getName(), ContentType.TEXT_PLAIN.withCharset("UTF-8"))
                    .addTextBody("id_number", requestEntity.getIdCard(), ContentType.TEXT_PLAIN)
                    .addBinaryBody("liveness_data_file", uploadFile.getBytes(), ContentType.DEFAULT_BINARY, uploadFile.getOriginalFilename())
                    .build();
            String result = HttpUtil.getInstance().requestMultipart(linkfaceConfig.getLivenessUrl(), null, entity);
            logger.info("RSP 调用【linkfack人脸比对-livenessVerification】 返回结果：res:{}", result);
            if (StringUtils.isNotBlank(result)) {
                JSONObject resultJson = JSONObject.parseObject(result);
                if (resultJson != null && StringUtils.equals("OK", resultJson.getString("status"))) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("hack_score", resultJson.getString("hack_score"));
                    params.put("verify_score", resultJson.getString("verify_score"));
                    params.put("liveness_data_id", resultJson.getString("liveness_data_id"));
                    return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, JSON.toJSONString(params));
                }
                String msg = LinkFaceEnum.getDesc(resultJson.getString("status")).getDecs();
                return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR.getErrorCode(), msg);
            }
            return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR);
        } catch (Exception e) {
            logger.error("jss调用【linkfack人脸比对】异常,livenessVerification,paramMap:{}", requestEntity, e);
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR);
        }
    }
}
